package com.ymatou.iapi.trading.sellerquery2.testcase;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.query.seller.trading.api.parameter.GetOrderProductAmountInfosBean;
import com.ymatou.query.seller.trading.api.parameter.GetOrderProductAmountInfosResponse;
import com.ymatou.query.seller.trading.api.parameter.GetOrderProductAmountInfosResponse.OrderProductAmountInfo;
import com.ymatou.query.seller.trading.api.service.OrderCreate;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymt.utils.tag.P2;
import com.ymt.utils.tag.P3;
import com.ymttest.database.sqlwapper.DefaultWapper;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.YMTDateUtil;

/**
 * @date 2016-09-06
 * @author songyefeng
 * @desc 根据商品Id获取订单中商品数量信息 接口已经转接java
 */
@TestSuite
public class Ts_GetOrderProductAmountInfos {

	private static GetOrderProductAmountInfosBean request;
	// private static
	// com.ymatou.query.seller.trading.api.service.GetOrderProductAmountInfosCall
	// call;
	private static com.ymatou.iapi.trading.sellerquery2.service.GetOrderProductAmountInfosCall call;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("根据商品Id获取订单中商品数量信息");
	}

	@Before
	public void caseUp() {
		request = new GetOrderProductAmountInfosBean();
		// call = new
		// com.ymatou.query.seller.trading.api.service.GetOrderProductAmountInfosCall();
		call = new com.ymatou.iapi.trading.sellerquery2.service.GetOrderProductAmountInfosCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(call.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	private void verify() {
		GetOrderProductAmountInfosResponse expectedResponse = new GetOrderProductAmountInfosResponse();
		ConstructExpectedResponse(expectedResponse);
		GetOrderProductAmountInfosResponse actualResponse = call
						.getOrderProductAmountInfosResponse();
		DataUtil.verifyEquals(expectedResponse.getAmountInfos().size(), actualResponse.getAmountInfos().size(),
						"验证AmountInfos的数量");
		Iterator<String> it = expectedResponse.getAmountInfos().keySet().iterator();
		while (it.hasNext()) {
			String actPid = it.next();
			GetOrderProductAmountInfosResponse.OrderProductAmountInfo actual = actualResponse.getAmountInfos().get(
							actPid);
			boolean exists = expectedResponse.getAmountInfos().containsKey(actPid);
			if (exists) {
				GetOrderProductAmountInfosResponse.OrderProductAmountInfo expect = expectedResponse.getAmountInfos()
								.get(actPid);
				DataUtil.verifyEquals(expect.getPaid(), actual.getPaid(), "验证ProductId: " + actPid + "的Paid值");
				DataUtil.verifyEquals(expect.getUnpaid(), actual.getUnpaid(), "验证ProductId: " + actPid + "的Unpaid值");
			}else{
				DataUtil.verifyEquals(0, actual.getPaid(), "验证ProductId: " + actPid + "的Paid值");
				DataUtil.verifyEquals(0, actual.getUnpaid(), "验证ProductId: " + actPid + "的Unpaid值");
			}
		}
	}

	@SuppressWarnings("rawtypes")
	private void ConstructExpectedResponse(GetOrderProductAmountInfosResponse response) {
		List<String> productIds = request.getProductIds().stream().distinct()
						.collect(Collectors.toList());
		List<Map> results = execute(productIds);
		ConvertResult(response, results);

	}

	@SuppressWarnings("rawtypes")
	private void ConvertResult(GetOrderProductAmountInfosResponse response, List<Map> results) {
		Map<String, GetOrderProductAmountInfosResponse.OrderProductAmountInfo> AmountInfos = new HashMap<String, GetOrderProductAmountInfosResponse.OrderProductAmountInfo>();
		if (DataUtil.isNullOrEmpty(request.getProductIds()) == false) {
			for (int i = 0; i < request.getProductIds().size(); i++) {
				String pid = request.getProductIds().get(i);
				GetOrderProductAmountInfosResponse.OrderProductAmountInfo o = new GetOrderProductAmountInfosResponse.OrderProductAmountInfo();
				o.setProductId(pid);
				boolean has = results.stream().anyMatch(x -> x.get("ProductId").equals(pid));
				if (has == false) {
					o.setPaid(0);
					o.setUnpaid(0);
					AmountInfos.put(o.getProductId(), o);   //productid不存在，设置为0, 如果不需要返回不存在的productid数据，则注释这行代码
				} else {
					Map match = results.stream().filter(x -> x.get("ProductId").equals(pid))
									.collect(Collectors.toList()).get(0);
					o.setPaid(DataUtil.Integerr.GetValueOrDefault(match.get("Paid")));
					o.setUnpaid(DataUtil.Integerr.GetValueOrDefault(match.get("Unpaid")));
					AmountInfos.put(o.getProductId(), o);
				}
			}
		}
		response.setAmountInfos(AmountInfos);
	}

	@SuppressWarnings("rawtypes")
	private List<Map> execute(List<String> productIds) {
		DefaultWapper defaultWapper = new DefaultWapper();
		String queryField = " oi.sproductId as ProductId";
		queryField += " , sum(IIF(o.itradingstatus = 1, oi.iAmount, 0)) as Unpaid";
		queryField += " , sum(IIF(o.itradingstatus in (2,3,4,16,17), oi.iAmount, 0)) as Paid";
		String joinCondition = " join ymt_orders(nolock) o on oi.iorderid = o.iorderid ";
		StringBuffer queryCondition = new StringBuffer();
		if (DataUtil.isNullOrEmpty(productIds) == false) {
			queryCondition.append(" oi.sproductId in " + DataUtil.toInOfSql(productIds));
		}
		if (request.getSellerId() != null && request.getSellerId() != 0) {
			queryCondition.append(" and o.iBuyerId = "+request.getSellerId());
		}
		if (request.getBeginTime() != null && request.getBeginTime() != "" && request.getEndTime() != null
						&& request.getEndTime() != "") {
			queryCondition.append(" and o.dAddTime >= '" + request.getBeginTime() + "'");
			queryCondition.append(" and o.dAddTime <= '" + request.getEndTime() + "'");
		}
		queryCondition.append(" group by oi.sproductId");
		return defaultWapper.selectOrderInfo(queryField, joinCondition, queryCondition.toString());
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetOrderProductAmountInfos_001() {
		Logger.start(true, "根据商品Id获取订单中商品数量信息");
		try {
			List<String> productIds = new ArrayList<String>();
			Logger.comment("准备前置数据");
			OrderCreate c = new OrderCreate();
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			productIds.add(c.create1_M2cOrder(userId, sellerId).getsProductId());
			productIds.add(c.create2_PayOrder(userId, sellerId).getsProductId());
			productIds.add(c.create3_ShippedOrder(userId, sellerId).getsProductId());
			productIds.add(c.create4_ReceivedOrder(userId, sellerId).getsProductId());
			productIds.add(c.create4_ApplyRefundOrder(userId, sellerId).getsProductId());
			productIds.add(c.create4_RefundOrder(userId, sellerId).getsProductId());
			Thread.sleep(3000l);
			Logger.comment("准备前置数据结束");
			request.setProductIds(productIds);
			call.setData(request);
			call.callService();
			Logger.verifyEquals("200", call.getCode(), "验证code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetOrderProductAmountInfos_002() {
		Logger.start(true, "根据商品Id获取订单中商品数量信息,productIds为空");
		try {
			List<String> productIds = new ArrayList<String>();
			request.setProductIds(productIds);
			call.setData(request);
			call.callService();
			DataUtil.verifyEquals(400, call.getCode(), "验证code");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetOrderProductAmountInfos_003() {
		Logger.start(true, "根据商品Id获取订单中商品数量信息,productId不存在");
		try {
			String productId = "meiyougaiproductid";
			List<String> productIds = new ArrayList<String>();
			productIds.add(productId);
			request.setProductIds(productIds);
			call.setData(request);
			call.callService();
			
			
			DataUtil.verifyEquals(200, call.getCode(), "验证code");
			GetOrderProductAmountInfosResponse response = call.getOrderProductAmountInfosResponse();
			Map<String, OrderProductAmountInfo> amountInfos =  response.getAmountInfos();
			boolean rightSize = amountInfos.size() == 1;
			DataUtil.verify(1, amountInfos.size(), "验证AmountInfos.size() == 1");
			if (rightSize) {
				boolean containKey = amountInfos.containsKey(productId);
				DataUtil.verify(true, containKey, "验证amountInfos存在key=["+productId+"]");
				if (containKey) {
					OrderProductAmountInfo info = amountInfos.get(productId);
					boolean notNull = info != null;
					DataUtil.verify(true, notNull, "验证amountInfos存在key=["+productId+"]的value != null");
					if (notNull) {
						DataUtil.verify(0, info.getPaid(), "验证amountInfos存在key=["+productId+"]的value.paid");
						DataUtil.verify(0, info.getUnpaid(), "验证amountInfos存在key=["+productId+"]的value.unpaid");
					}
				}
			}
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetOrderProductAmountInfos_004() {
		Logger.start(true, "根据商品Id获取订单中商品数量信息");
		try {
			List<String> productIds = new ArrayList<String>();
			Logger.comment("准备前置数据");
			productIds.add("1234567");
			Logger.comment("准备前置数据结束");
			request.setProductIds(productIds);
			call.setData(request);
			call.callService();
			Logger.verifyEquals("200", call.getCode(), "验证code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetOrderProductAmountInfos_005() {
		Logger.start(true, "根据商品Id和sellerid获取订单中商品数量信息");
		try {
			List<String> productIds = new ArrayList<String>();
			Logger.comment("准备前置数据");
			OrderCreate c = new OrderCreate();
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			int sellerId2 = Integer.valueOf(EnvSetup.getData("SellerId2"));
			productIds.add(c.create1_M2cOrder(userId, sellerId).getsProductId());
			productIds.add(c.create2_PayOrder(userId, sellerId).getsProductId());
			productIds.add(c.create3_ShippedOrder(userId, sellerId).getsProductId());
			productIds.add(c.create4_ReceivedOrder(userId, sellerId2).getsProductId());
			productIds.add(c.create4_ApplyRefundOrder(userId, sellerId2).getsProductId());
			productIds.add(c.create4_RefundOrder(userId, sellerId2).getsProductId());
			Thread.sleep(3000l);
			Logger.comment("准备前置数据结束");
			request.setProductIds(productIds);
			request.setSellerId(sellerId);
			call.setData(request);
			call.callService();
			Logger.verifyEquals("200", call.getCode(), "验证code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetOrderProductAmountInfos_006() {
		Logger.start(true, "根据商品Id,beginTime,endTime获取订单中商品数量信息");
		try {
			List<String> productIds = new ArrayList<String>();
			Logger.comment("准备前置数据");
			OrderCreate c = new OrderCreate();
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			productIds.add(c.create1_M2cOrder(userId, sellerId).getsProductId());
			productIds.add(c.create2_PayOrder(userId, sellerId).getsProductId());
			productIds.add(c.create3_ShippedOrder(userId, sellerId).getsProductId());
			productIds.add(c.create4_ReceivedOrder(userId, sellerId).getsProductId());
			productIds.add(c.create4_ApplyRefundOrder(userId, sellerId).getsProductId());
			productIds.add(c.create4_RefundOrder(userId, sellerId).getsProductId());
			Thread.sleep(3000l);
			Logger.comment("准备前置数据结束");
			request.setProductIds(productIds);
			request.setBeginTime(YMTDateUtil.getBeforeOrNextMonth(-1, YMTDateUtil.YMDTHMS_STRING));
			request.setEndTime(YMTDateUtil.getBeforeOrNextMonth(0, YMTDateUtil.YMDTHMS_STRING));
			call.setData(request);
			call.callService();
			Logger.verifyEquals("200", call.getCode(), "验证code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P2.class)
	@TestCase
	public void Tc_GetOrderProductAmountInfos_007() {
		Logger.start(true, "根据商品Id,sellerid,beginTime,endTime和sellerid获取订单中商品数量信息");
		try {
			List<String> productIds = new ArrayList<String>();
			Logger.comment("准备前置数据");
			OrderCreate c = new OrderCreate();
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			int sellerId2 = Integer.valueOf(EnvSetup.getData("SellerId2"));
			productIds.add(c.create1_M2cOrder(userId, sellerId).getsProductId());
			productIds.add(c.create2_PayOrder(userId, sellerId).getsProductId());
			productIds.add(c.create3_ShippedOrder(userId, sellerId).getsProductId());
			productIds.add(c.create4_ReceivedOrder(userId, sellerId2).getsProductId());
			productIds.add(c.create4_ApplyRefundOrder(userId, sellerId2).getsProductId());
			productIds.add(c.create4_RefundOrder(userId, sellerId2).getsProductId());
			Thread.sleep(3000l);
			Logger.comment("准备前置数据结束");
			request.setProductIds(productIds);
			request.setSellerId(sellerId);
			request.setBeginTime(YMTDateUtil.getBeforeOrNextMonth(-1, YMTDateUtil.YMDTHMS_STRING));
			request.setEndTime(YMTDateUtil.getBeforeOrNextMonth(0, YMTDateUtil.YMDTHMS_STRING));
			call.setData(request);
			call.callService();
			Logger.verifyEquals("200", call.getCode(), "验证code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetOrderProductAmountInfos_008() {
		Logger.start(true, "beginTime=\"\",endTime=\"\",获取订单中商品数量信息");
		try {
			List<String> productIds = new ArrayList<String>();
			Logger.comment("准备前置数据");
			OrderCreate c = new OrderCreate();
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			productIds.add(c.create1_M2cOrder(userId, sellerId).getsProductId());
			productIds.add(c.create2_PayOrder(userId, sellerId).getsProductId());
			Thread.sleep(3000l);
			Logger.comment("准备前置数据结束");
			request.setProductIds(productIds);
			request.setBeginTime("");
			request.setEndTime("");
			call.setData(request);
			call.callService();
			Logger.verifyEquals("200", call.getCode(), "验证code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetOrderProductAmountInfos_009() {
		Logger.start(true, "sellerid=0获取订单中商品数量信息");
		try {
			List<String> productIds = new ArrayList<String>();
			Logger.comment("准备前置数据");
			OrderCreate c = new OrderCreate();
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			productIds.add(c.create1_M2cOrder(userId, sellerId).getsProductId());
			Thread.sleep(3000l);
			Logger.comment("准备前置数据结束");
			request.setProductIds(productIds);
			request.setSellerId(0);
			call.setData(request);
			call.callService();
			Logger.verifyEquals("200", call.getCode(), "验证code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetOrderProductAmountInfos_010() {
		Logger.start(true, "只传beginTime,不传endTime,获取订单中商品数量信息");
		try {
			List<String> productIds = new ArrayList<String>();
			Logger.comment("准备前置数据");
			OrderCreate c = new OrderCreate();
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			productIds.add(c.create1_M2cOrder(userId, sellerId).getsProductId());
			Thread.sleep(3000l);
			Logger.comment("准备前置数据结束");
			request.setProductIds(productIds);
			request.setSellerId(sellerId);
			request.setBeginTime(YMTDateUtil.getBeforeOrNextMonth(1, YMTDateUtil.YMDTHMS_STRING));
			call.setData(request);
			call.callService();
			Logger.verifyEquals("200", call.getCode(), "验证code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P3.class)
	@TestCase
	public void Tc_GetOrderProductAmountInfos_011() {
		Logger.start(true, "只传endTime,不传beginTime,获取订单中商品数量信息");
		try {
			List<String> productIds = new ArrayList<String>();
			Logger.comment("准备前置数据");
			OrderCreate c = new OrderCreate();
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			productIds.add(c.create1_M2cOrder(userId, sellerId).getsProductId());
			Thread.sleep(3000l);
			Logger.comment("准备前置数据结束");
			request.setProductIds(productIds);
			request.setSellerId(sellerId);
			request.setEndTime(YMTDateUtil.getBeforeOrNextMonth(-1, YMTDateUtil.YMDTHMS_STRING));
			call.setData(request);
			call.callService();
			Logger.verifyEquals("200", call.getCode(), "验证code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

}